<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      div {
        width: 200px;
        height: 200px;
        background-color: orange;
        position: absolute;
        left: 200px;
        top: 200px;
      }
    </style>
  </head>
  <body>
    <div></div>

    <script>
      var startX = 0;
      var startY = 0;
      var lock = false;
      var div = document.querySelector("div");
      div.onmousemove = function (e) {
        if (lock) {
          // 计算偏差值，移动对象位置
          div.style.left = parseInt(document.defaultView.getComputedStyle(div)["left"]) +(e.clientX - startX) + "px";
          div.style.top = parseInt(document.defaultView.getComputedStyle(div)["top"]) +(e.clientY - startY) + "px";
          // 每次移动都及时更新鼠标初始位置，因为上面的定位是实时获取left、top值来实现定位显示的，每次移动都是最新定位，所以每次移动都需要获取最新的移动距离，而不是初始距离，那样会使得每次移动跨度都非常大；
          startX=e.clientX;
          startY=e.clientY;
        }
      };
      div.onmousedown = function (e) {
        lock = true;
        // 获取鼠标初始坐标
        startX = e.clientX;
        startY = e.clientY;
      };
      div.onmouseup = function () {
        lock = false;
      };
    </script>
  </body>
  <script></script>
</html>
